package com.whalefin.service;

import com.whalefin.domain.Advertise;
import com.whalefin.domain.BaiDuPush;
import com.whalefin.domain.LeaveMessage;
import com.whalefin.domain.User;
import com.whalefin.persistence.AdvertiseMapper;
import com.whalefin.persistence.BaiDuPushMapper;
import com.whalefin.persistence.LeaveMessageMapper;
import com.whalefin.persistence.UserMapper;

import com.whalefin.service.tools.ApplicationParams;
import com.whalefin.service.tools.BooleanResult;
import com.whalefin.service.tools.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import java.util.*;


@Controller
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SmsService smsService;
    @Autowired
    private LeaveMessageMapper leaveMessageMapper;
    @Autowired
    private AdvertiseMapper advertiseMapper;
    @Autowired
    private BaiDuPushMapper baiDuPushMapper;



    /**
     * 注册新用户
     * @param username 用户名
     * @param loginPassword 密码
     * @param address 地址
     * @param phoneNum 电话
     * @param age 年龄
     * @return
     */
//    @RequestMapping(method = RequestMethod.POST, value = "/registerUser")
//    public @ResponseBody
//    BooleanResult registerUser(@RequestParam String username,@RequestParam String loginPassword,@RequestParam String address,
//                               @RequestParam String phoneNum,@RequestParam Integer age) {
//        Date date = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        //非空验证
//        if(username == null || "".equals(username)){
//            return new BooleanResult(false,"用户名不能为空!");
//        }else if(userMapper.checkUser(username) > 0){
//            return new BooleanResult(false,"该用户名已注册!");
//        }
//        if(loginPassword == null || "".equals(loginPassword)){
//            return new BooleanResult(false,"密码不能为空!");
//        }
//        //组装数据
//        User user = new User();
//        user.setUsername(username);
//        user.setLoginPassword(loginPassword);
//        user.setAddress(address);
//        user.setPhoneNum(phoneNum);
//        user.setAge(age);
//        user.setCreatetime(sdf.format(date));
//        //结果判断
//        int i = userMapper.registerUser(user);
//        if (i == 1) {
//            return new BooleanResult(true,"注册成功!");
//        } else {
//            return new BooleanResult(false,"注册失败!");
//        }
//    }


    /**
     * 上传手机号，生成验证码，发送验证码
     * @param phoneNum
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/sendVerifyCode")
    public @ResponseBody BooleanResult registerUser(@RequestParam String[] phoneNum){
        // 检验上传电话是否为空
        if (phoneNum.equals("") || phoneNum == null) {
            return new BooleanResult(false, "手机号不能为空!");
        }
        // 检验上传号码是否存在(已注册)
        if(userMapper.queryUserPhoneNum(phoneNum) != 0){
            return new BooleanResult(false,"此号码已经被注册!");
        }else {
            userMapper.insertPhoneNum(phoneNum);
            // 生成4位随机码
            String code = String.valueOf(RandomUtil.createVerifyCode());
            List<User> idList = userMapper.queryIdByPhoneNum(phoneNum);
            int id = 0;
            for(int i=0;i<idList.size();i++){
                id = idList.get(i).getId();
                userMapper.updateCode(id, code);
            }
            String smsContent = "您的验证码是:"+code;
            // 发送验证码到手机
            boolean  result = true;
            //2.发送短信
            Calendar cal = Calendar.getInstance();
            //延时4小时发送
            cal.add(Calendar.SECOND,5);
            try {
                result = smsService.sendScheduledSMS(phoneNum, smsContent,cal.getTime());
            }catch (Exception e){
                e.printStackTrace();
            }
            if (result) {
                return new BooleanResult(true, "发送成功!");
            } else {
                return new BooleanResult(false, "发送失败!");
            }
        }
    }

    /**
     * 注册用户
     * @param phoneNum
     * @param code
     * @param password
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/registerUser")
    public @ResponseBody BooleanResult registerUser(@RequestParam String phoneNum,@RequestParam String code,@RequestParam String password){
        if(phoneNum == null || "".equals(phoneNum)){
            return new BooleanResult(false,"手机号码不能为空!");
        }
        if(password == null || "".equals(password)){
            return new BooleanResult(false,"密码不能为空!");
        }
        // 检验验证码是否存在
        if (code == null || code.equals("")) {
            return new BooleanResult(false, "验证码不能为空!");
        } else {
            int resultCode = userMapper.queryVerifyCode(code,phoneNum);
            if (resultCode > 0) {
                if(userMapper.queryPhoneNum(phoneNum) != 0){
                    return new BooleanResult(false,"手机号码已被注册!");
                }else {
                    int r =userMapper.insertIntoUser(phoneNum, password, code);
                    if(r > 0){
                        return new BooleanResult(true, "注册成功!");
                    }else {
                        return new BooleanResult(false,"注册失败!");
                    }
                }
            } else {
                return new BooleanResult(false, "验证码不存在!");
            }
        }
    }


//        /**
//     * 检验验证码是否存在
//     *
//     * @param code 验证码
//     * @return 验证码校验成功/验证码校验失败
//     */
//    @RequestMapping(method = RequestMethod.POST, value = "/checkVerifyCode")
//    public @ResponseBody BooleanResult checkVerifyCode(@RequestParam String code) {
//        // 检验验证码是否存在
//        if (code == null || code.equals("")) {
//            return new BooleanResult(false, "验证码不能为空!");
//        } else {
//            int result = userMapper.queryVerifyCode(code);
//            if (result > 0) {
//                return new BooleanResult(true, "验证码校验成功!");
//            } else {
//                return new BooleanResult(false, "验证码不存在!");
//            }
//        }
//    }


    /**
     * 用户登录
     * @param phoneNum
     * @param loginPassword
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/userLogin")
    public @ResponseBody
    BooleanResult userLogin(@RequestParam String phoneNum,String loginPassword,@RequestParam(required = false) String pushKey,@RequestParam(required = false) Integer deviceType){
        //非空判断
        if(phoneNum == null || "".equals(phoneNum)){
            return new BooleanResult(false,"用户名不能为空!");
        }
        if(loginPassword == null || "".equals(loginPassword)){
            return new BooleanResult(false,"密码不能为空!");
        }
        //验证用户是否存在
        User user = userMapper.userLogin(phoneNum,loginPassword);
        if(user != null || "".equals(user)){
            User returnUser = new User();
            returnUser.setId(user.getId());
            returnUser.setLoginPassword("");
            returnUser.setIndexPage(0);
            returnUser.setPageSize(0);
            if(user.getUsername() != null){
                returnUser.setUsername(user.getUsername());
            }else {
                returnUser.setUsername("");
            }
            returnUser.setCreatetime(user.getCreatetime());
            if(user.getAddress() != null){
                returnUser.setAddress(user.getAddress());
            }else {
                returnUser.setAddress("");
            }
            if(user.getLng() != null){
                returnUser.setLng(user.getLng());
            }else {
                returnUser.setLng(0.0);
            }
            if(user.getLat() != null){
                returnUser.setLat(user.getLat());
            }else {
                returnUser.setLat(0.0);
            }
            if(user.getUserpic() != null){
                returnUser.setUserpic(user.getUserpic());
            }else {
                returnUser.setUserpic("");
            }
            if(user.getDistance() != null){
                returnUser.setDistance(user.getDistance());
            }else {
                returnUser.setDistance(0.0);
            }
            if(user.getGender() != null){
                returnUser.setGender(user.getGender());
            }else {
                returnUser.setGender("");
            }
            if(user.getPhoneNum() != null){
                returnUser.setPhoneNum(user.getPhoneNum());
            }else {
                returnUser.setPhoneNum("");
            }

            if(pushKey != null && deviceType != 0){

                baiDuPushMapper.setPushListNull(pushKey);
                BaiDuPush myPush =  baiDuPushMapper.queryPushUser(returnUser.getId());
                if (myPush != null){
                    baiDuPushMapper.updatePushUser(returnUser.getId(),pushKey,deviceType);
                }else {
                    baiDuPushMapper.addPushUser(returnUser.getId(),pushKey,deviceType);
                }
            }

            BooleanResult booleanResult = new BooleanResult(true,"登录成功!");
            booleanResult.getResultMap().put("user",returnUser);
            return booleanResult;
        }else {
            return new BooleanResult(false,"用户不存在或密码输入有误!");
        }
    }

    /**
     * 用户信息设置
     * @param username 昵称
     * @param gender 性别
     * @param address 地址

     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/setUser")
    public @ResponseBody BooleanResult setUser(@RequestParam String username,@RequestParam String gender,@RequestParam(required = false) String address,
                                              @RequestParam Integer userId,@RequestParam(required = false) MultipartFile userPic) throws IOException{

        User userMsg = userMapper.queryUserByUserId(userId);
        User user = new User();
        if(username != null ){
            user.setUsername(username);
        }else {
            user.setUsername(userMsg.getUsername());
        }
        if(gender != null){
            user.setGender(gender);
        }else {
            user.setGender(userMsg.getGender());
        }
        if(address != null){
            user.setAddress(address);
        }else {
            user.setAddress(userMsg.getAddress());
        }

        if (userPic != null && userPic.getSize() > 0) {
            String fileName = StringUtils.isBlank(genFileName(userPic)) ? "": genFileName(userPic);
            FileCopyUtils.copy(userPic.getBytes(), new File(genFilePath(fileName)));
            user.setUserpic(fileName);
        }else {
            user.setUserpic(userMsg.getUserpic());
        }
        user.setId(userId);
        int result = userMapper.updateUserMsg(user);
        if(result > 0){
            return new BooleanResult(true,"用户信息设置成功!");
        }else {
            return new BooleanResult(false,"用户信息设置失败!");
        }
    }


    /**
     * 修改密码
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value ="/changePassword")
    public @ResponseBody BooleanResult changePassword(@RequestParam Integer userId,@RequestParam String oldPassword,@RequestParam String newPassword){
        User user = userMapper.queryUserByPassword(oldPassword,userId);
        if( user != null){
           int result = userMapper.updatePassword(newPassword,userId);
            if(result > 0){
                return new BooleanResult(true,"密码修改成功!");
            }else {
                return new BooleanResult(false,"密码修改失败!");
            }
        }else {
            return new BooleanResult(false,"旧密码输入有误!");
        }
    }


    /**
     * 我发布的
     * @param userId 用户id
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/MyRelease")
    public @ResponseBody BooleanResult MyRelease(@RequestParam Integer userId){
        List list = new ArrayList();

        List<LeaveMessage> leaveMessageList = leaveMessageMapper.queryLeaveMsgById(userId);

        for(int i=0;i<leaveMessageList.size();i++){
            LeaveMessage leaveMessage = new LeaveMessage();
            leaveMessage.setId(leaveMessageList.get(i).getId());
            leaveMessage.setSchoolNum("");
            leaveMessage.setLat(0.0);
            leaveMessage.setIndexPage(0);
            leaveMessage.setLng(0.0);
            leaveMessage.setCreatetime(leaveMessageList.get(i).getCreatetime());
            leaveMessage.setMsg_content(leaveMessageList.get(i).getMsg_content());
            leaveMessage.setMsg_pic(leaveMessageList.get(i).getMsg_pic());
            leaveMessage.setMsg_title(leaveMessageList.get(i).getMsg_title());
            leaveMessage.setPageSize(0);
            leaveMessage.setReadCount(leaveMessageList.get(i).getReadCount());
            leaveMessage.setReplyNum(leaveMessageList.get(i).getReplyNum());
            leaveMessage.setStatus("");
            leaveMessage.setUserId(leaveMessageList.get(i).getUserId());
            leaveMessage.setTotaluserId("");
            list.add(leaveMessage);
        }

        List<Advertise> advertiseList = advertiseMapper.queryAdvertisesById(userId);

        for(int j=0;j<advertiseList.size();j++){
            Advertise advertise = new Advertise();
            advertise.setSchoolNum("");
            advertise.setTotaluserId("");
            advertise.setLat(0.0);
            advertise.setLng(0.0);
            advertise.setUserId(advertiseList.get(j).getUserId());
            advertise.setAd_content(advertiseList.get(j).getAd_content());
            advertise.setAd_pic(advertiseList.get(j).getAd_pic());
            advertise.setAd_title(advertiseList.get(j).getAd_title());
            advertise.setCreatetime(advertiseList.get(j).getCreatetime());
            advertise.setId(advertiseList.get(j).getId());
            advertise.setIndexPage(0);
            advertise.setPageSize(0);
            advertise.setReplyNum(advertiseList.get(j).getReplyNum());
            advertise.setReadCount(advertiseList.get(j).getReadCount());
            advertise.setStatus("");
            advertise.setTotaluserId("");
            list.add(advertise);
        }


        if(list.size() > 0){
            BooleanResult booleanResult = new BooleanResult(true,"我发布的留言和广告");
            booleanResult.getResultMap().put("list",list);
            return booleanResult;
        }else {
            return new BooleanResult(false,"你没有发布任何信息");
        }
    }


    /**
     * 忘记密码
     * @param code
     * @param newPassword
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/forgetPassword")
    public @ResponseBody BooleanResult forgetPassword(@RequestParam String code,@RequestParam String newPassword,@RequestParam String phoneNum){
        if(code != null){
            int result = userMapper.queryVerifyCode(code,phoneNum);
            if(result > 0){
                int changeResult = userMapper.updateUserPassword(phoneNum,newPassword);
                if(changeResult > 0){
                    return new BooleanResult(true,"新密码设置成功");
                }else {
                    return new BooleanResult(false,"密码设置失败");
                }
            }else {
                return new BooleanResult(false,"验证码不存在");
            }
        }else {
            return new BooleanResult(false, "验证码不能为空");
        }
    }


    /**
     * 我的消息
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/MyMsg")
    public @ResponseBody BooleanResult MyMsg(@RequestParam Integer userId){

        return null;
    }


    /**
     * 用户上传经纬度
     * @param userId 用户id
     * @param lng 经度
     * @param lat 纬度
     */
//    @RequestMapping(method = RequestMethod.POST,value = "/uploadUserLocation")
//    public @ResponseBody
//    BooleanResult uploadUserLocation(@RequestParam Integer userId,@RequestParam Double lng,@RequestParam Double lat){
//        BigDecimal lngFirst=new BigDecimal(Double.toString(lng));
//        Double lngLocation=lngFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位经度
//
//        BigDecimal latFirst=new BigDecimal(Double.toString(lat));
//        Double latLocation=latFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位纬度
//
//        int result = userMapper.updateUserLocation(lngLocation, latLocation, userId);//更新数据库 用户经纬度
//        if(result > 0){
//            return new BooleanResult(true,"经纬度上传成功!");
//        }else {
//            return new BooleanResult(false,"经纬度上传失败!");
//        }
//    }


    /**
     * 用户上传头像
     * @param userId
     * @param userPic
     * @return
     * @throws java.io.IOException
     */
//    @RequestMapping(method = RequestMethod.POST,value = "/uploadUserPic")
//    public @ResponseBody
//    BooleanResult uploadUserPic(@RequestParam Integer userId,@RequestParam(required = false) MultipartFile userPic) throws IOException{
//        if (userPic != null && userPic.getSize() > 0) {
//            String fileName = StringUtils.isBlank(genFileName(userPic)) ? "": genFileName(userPic);
//            FileCopyUtils.copy(userPic.getBytes(), new File(genFilePath(fileName)));
//            int result = userMapper.updateUserPic(fileName, userId);
//            if(result > 0){
//                return new BooleanResult(true,"头像上传成功!");
//            }else {
//                return new BooleanResult(false,"头像上传失败!");
//            }
//        }else {
//            return new BooleanResult(false,"没有图片文件!");
//        }
//    }


    //计算地图上两点距离辅助方法
    private static final double EARTH_RADIUS = 6378.137;// 赤道半径(单位m)

    /**
     * 转化为弧度(rad)
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    private String genFilePath(String fileName) {
        return ApplicationParams.IMG_SAVE_FOLDER + fileName;
    }

    private String genFileName(MultipartFile file) {
        // 使用时间做文件的prefix，防止文件冲突;
        String prefix = String.valueOf(new Date().getTime());
        return prefix + "-" + UUID.randomUUID();
    }


    /**
     *
     * 以下方法后台使用
     */
    //用户总数
    public int totalCountUser(){
        return userMapper.totalCountUser();
    }

    //所有用户信息
    public List<User> queryUserByCondition(Integer indexPage,Integer pageSize){
        return userMapper.queryUserByCondition(indexPage,pageSize);
    }

    //根据条件查询用户总数
    public int totalCountByUser(User user){
        return userMapper.totalCountByUser(user);
    }

    //根据条件查询用户信息
    public List<User> queryAllUserByUser(User user){
        return userMapper.queryAllUserByUser(user);
    }
}